<?php
/**
 *
 *
 */
namespace Yz\modules\Users;
use Yz_String,
    Yz_Hash,
    Error,
    TypeError,
    ValueError,
    AccessError
;
class Controller_ChangePassword
    extends \Yz\modules\Generic\Controller_AbstractUpdate
{

    /**
     *  forbid access unless autenticated
     *
     */
    const ACCESS = \Yz_Access_Interface::AC_VALID_USER;

    protected $model;
    protected $modelName = 'User';

    /** No arguments required
     *  @var array
     */
    protected $arguments = array(
    );

    /**************************
     *    Protected methods   *
     **************************/


    /**
     *
     */
    protected function fetchData()
    {
        $this->item = \Yz_User_Default::getInstance()->getUserInfo();
        return $this;
    }



    /** process the POST input to obtain old and new passwords
     *      Use the following POST arguments:
     *      - oldPassword
     *      - newPassword
     *      - repeatPassword
     *  @param Yz_Hash $post
     *  @return this
     */
    protected function processData(Yz_Hash $post)
    {
        // prevent verifyPassword from throwing InvalidValueType
        $oldpw = Yz_String::valueOf($post->oldPassword);
        try {
            // throws user_exception
            if (! $this->item->verifyPassword($oldpw))
                throw AccessError::_new_(array('path' => $this->name));
            $newpw = $post->newPassword;
            $newpw2 = $post->repeatPassword;
            if (! is_string($newpw) or ! is_string($newpw2))
                throw TypeError::_new_();

            if ($newpw2 !== $newpw)
                throw ValueError::_new_();
            $this->item->setPassword($newpw);
        } catch (Error $ex) {
            // TODO modify errorMessage, specifying the reason
            $this->error = $ex;
        }
        return $this;
    }

    /**
     *
     */
    protected function getErrorMessage()
    {
        $msg = parent::getErrorMessage();
        switch (true) {
            case $this->error instanceof AccessError:
                $msg .= ':WrongPassword';
                break;
            case $this->error instanceof TypeError:
            case $this->error instanceof ValueError:
                $msg .= ':PasswordsDontMatch';
                break;
            default:
        }
        return $msg;
    }

}
